package com.example.baseapp.business.validator;


import com.example.baseapp.business.entity.User;
import com.example.baseapp.business.interfaces.NotConflictUser;
import com.example.baseapp.business.interfaces.UniqueUser;
import com.example.baseapp.business.service.UserService;
import lombok.extern.slf4j.Slf4j;

import javax.annotation.Resource;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.lang.annotation.Annotation;
import java.util.Collection;
import java.util.function.Predicate;

/**
 * UserValidation class
 *
 * @author zhangl
 * @date 2022/3/15 14:45
 */
@Slf4j
public class UserValidation <T extends Annotation> implements ConstraintValidator<T, User> {
    protected Predicate<User> predicate = c -> true;
    @Resource
    protected UserService userService;
    @Override
    public boolean isValid(User user, ConstraintValidatorContext constraintValidatorContext) {
        log.warn("开始校验.... :{}",user);
        return userService == null || predicate.test(user);
    }

    public static class  UniqueUserValidator extends UserValidation<UniqueUser> {

        @Override
        public void initialize(UniqueUser uniqueUser) {
            log.info("UniqueUser initialize ...");
            predicate = c-> {
                log.info("UniqueUserValidator ... {}",c);
                boolean flag = !userService.existUser(c);
                log.debug("result : {}",flag);
                return flag;
            };
        }
    }
    public static class NotConflictUserValidator extends UserValidation<NotConflictUser>{
        @Override
        public void initialize(NotConflictUser notConflictUser) {
            predicate = user -> {
                Collection<User> collection = userService.findByUserNameOrEmailOrTel(user);
                return collection.isEmpty() ||
                        (collection.size() == 1 && collection.iterator().next().getId().compareTo(user.getId()) == 0);

            };
        }
    }
}
